package com.fone.player.view;

import android.content.Context;
import android.content.res.ColorStateList;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.fone.player.R;
import com.fone.player.activity.personal.UserInfoActivity;
import com.fone.player.client.Callback;
import com.fone.player.client.Error;
import com.fone.player.client.Request;
import com.fone.player.client.Rst;
import com.fone.player.sns.UserInfoManager;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.util.LoginUtil;
import com.fone.player.util.ScreenUtil;

public class ChangeNickNameDialog implements OnClickListener {
	
	private static final String TAG = "ChangeNickNameDialog";
	
	private EditText change_name_et;
	private UserInfoActivity mActivity;
	private CustomDialog dialog;
	
	private String tempNickName;
	
	private Button changeSureBtn;
	private Button changeCancelBtn;
	
	private ColorStateList mColorStateList;
	
	public ChangeNickNameDialog(Context mContext, UserInfoActivity activity) {
		mActivity = activity; 
		
		mColorStateList = createColorStateList( 0xff555555, 0xffec6810);
		
		View changeNameView = LayoutInflater.from(mContext).inflate(
				R.layout.personal_change_name_dialog, null);
		dialog = new CustomDialog((Context) activity,
				changeNameView);
		dialog.setCanceledOnTouchOutside(false);

		dialog.show();

		changeNameView.setMinimumWidth((int) (ScreenUtil
				.getScreenWidthPix(mContext) * 0.8));// 设置dialog的宽度

		change_name_et = (EditText) changeNameView
				.findViewById(R.id.change_name_et);
		
		changeSureBtn = (Button) changeNameView
				.findViewById(R.id.change_name_sure_id);
		changeSureBtn.setOnClickListener(this);

		changeCancelBtn = (Button) changeNameView
				.findViewById(R.id.change_name_cancel_id);
		changeCancelBtn.setOnClickListener(this);
		
		change_name_et.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {}
			@Override
			public void afterTextChanged(Editable s) {
				
				if(change_name_et.getText().toString().trim().equals(UserInfoManager.getUserNickName())){
					changeSureBtn.setClickable(false);
					changeSureBtn.setTextColor(0xffc1c3c6);
				}else{
					changeSureBtn.setTextColor(mColorStateList);
					changeSureBtn.setClickable(true);
				}
			}
		});

		if(UserInfoManager.isLogin()){
			change_name_et.setText(UserInfoManager.getUserNickName());
			change_name_et.setSelection(UserInfoManager.getUserNickName().length());
		}
		
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.change_name_sure_id:
			if(FoneUtil.isNetOkWithToast(mActivity.getApplicationContext())){
				try {
					String nickName = change_name_et.getText().toString().trim();
					if(TextUtils.isEmpty(nickName)){
						FoneUtil.showToast(mActivity.getApplicationContext(), "请输入昵称");
						return;
					}
					if (!LoginUtil.checkNickName(nickName)) {
						Toast.makeText(mActivity.getApplicationContext(), "昵称太短或太长", Toast.LENGTH_SHORT).show();
						return;
					}
					if(nickName.equals(UserInfoManager.getUserNickName())){
						Toast.makeText(mActivity.getApplicationContext(), "与原昵称相同", Toast.LENGTH_SHORT).show();
						return;
					}
					
					tempNickName = nickName;
					String newvalue = FoneUtil.Base64Encode(nickName);
					mActivity.mHandler.sendEmptyMessage(UserInfoActivity.SHOW_WAITTING);
					Request.getInstance().updateuser(0, "", newvalue, new changeNameCallback());
				} catch (Exception e) {
					e.printStackTrace();
					L.e(TAG, "onClick", e.getMessage());
				}
				dialog.cancel();
			}
			break;
		case R.id.change_name_cancel_id:
			dialog.cancel();
			break;

		default:
			break;
		}
	}

	
	private class changeNameCallback implements Callback<Rst>{

		@Override
		public void onSuccess(Rst t) {
			// TODO Auto-generated method stub
			L.v(TAG, "changeNameCallback onSuccess", t.toString());
			if(t.result!=0){
				if(t.error!=null){
					L.v(TAG, "onSuccess","errorcode : "+ t.error.errorcode);
					try{
						switch (Integer.valueOf(t.error.errorcode)) {
						case 112:
							FoneUtil.showToast(mActivity.getApplicationContext(), "昵称不符合要求，请更换");
							break;
						case 707:
							FoneUtil.showToast(mActivity.getApplicationContext(), "抱歉，昵称已存在，请重新填写");
							break;
						default:
							FoneUtil.showToast(mActivity.getApplicationContext(), "昵称修改失败");
							break;
						}
					}catch(Exception e){
						FoneUtil.showToast(mActivity.getApplicationContext(), "昵称修改失败");
					}
					mActivity.mHandler.sendEmptyMessage(UserInfoActivity.CANCEL_WAITTING);
					tempNickName = null;
					return;
				}
			}
			new Thread(){
				public void run() {
					UserInfoManager.saveUserNickName(tempNickName);
					mActivity.mHandler.obtainMessage(UserInfoActivity.CHANGE_NICKNAME_SUCCESS, new String(tempNickName)).sendToTarget();
					tempNickName = null;
				};
			}.start();
		}

		@Override
		public void onFailure(Error error) {
			// TODO Auto-generated method stub
			mActivity.mHandler.sendEmptyMessage(UserInfoActivity.CANCEL_WAITTING);
			L.v(TAG,
					"changeNameCallback onFailure",
					"isNetworkError : " + error.isNetworkError() + " status : "
							+ error.getStatus() + " reason : "
							+ error.getReason());
			mActivity.mHandler.sendEmptyMessage(UserInfoActivity.CANCEL_WAITTING);
			tempNickName = null;
			
			if(error.isNetworkError()){
				FoneUtil.showToast(mActivity.getApplicationContext(), "网络超时,请稍后重试");
				return ;
			}
			FoneUtil.showToast(mActivity.getApplicationContext(), "请求失败");
			tempNickName = null;
		}
		
	}
	
	
    /**
     * 创建text的ColorStateList
     * @param normal 	正常状态颜色  (16进制数字)
     * @param pressed	下按状态颜色	(16进制数字)
     * @return
     */
    private ColorStateList createColorStateList(int normal, int pressed) {  
        int[] colors = new int[] { pressed, normal, normal };  
        int[][] states = new int[3][];  
        states[0] = new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled };  
        states[1] = new int[] { android.R.attr.state_enabled };  
        states[2] = new int[] {};  
        ColorStateList colorList = new ColorStateList(states, colors);  
        return colorList;  
    }  
	
}
